<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-工序质检项`"
		width="540px"
		:show-content-loading="showLoading"
		:save-btn-loading="saveBtnLoading"
		append-to-body
		:show-confirm-btn="false"
		:show-save-btn="true"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-save="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="工序" prop="processId">
						<el-select v-model="ruleForm.processId" class="width-100-percent" placeholder="工序" @change="onProcessListChange">
							<el-option
								v-for="item in processList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<jk-table border :data="ruleForm.itemList" :max-height="dialogTableHeight - 20">
			<vxe-column title="操作" align="center" field="processName" :width="120">
				<template slot="header">
					<el-button type="text" size="mini" @click="onAddBtn">添加</el-button>
				</template>
				<template slot-scope="scope">
					<div class="flex-center">
						<jk-button type="default" class="item-gap" icon="el-icon-plus" size="mini" @click="ruleForm.itemList.push({})"></jk-button>
						<jk-button type="default" icon="el-icon-minus" size="mini" @click="ruleForm.itemList.splice(scope.rowIndex, 1)"></jk-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="序号" type="seq" align="center" :width="80"> </vxe-column>
			<vxe-column title="指标" align="left" field="name" :min-width="160">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.name" size="mini"></jk-input>
				</template>
			</vxe-column>
		</jk-table>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinQualityIndexCreate,
        spinQualityIndexGet,
        spinQualityIndexUpdate
    } from '../../../api/quality/processQualityItems';
    export default {
        components: {
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                hasDuplicates: false,
                processList: [],
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    processName: '',
                    processCode: '',
                    processId: '',
                    workshopId: null,
                    itemList: [
                        { Id: 1, name: '条干' },
                        { Id: 2, name: '重量' },
                        { Id: 3, name: '棉结' }
                    ]
                },
                rules: {
                    processId: [{ required: true, trigger: 'change' }]
                },
                selectRowIndex: null
            };
        },
        methods: {
            onProcessListChange(e) {
                this.processList.forEach(x => {
                    if (e === x.id) {
                        this.$set(this.ruleForm, 'processName', x.name);
                        this.$set(this.ruleForm, 'processCode', x.code);
                    }
                });
            },
            onAddBtn() {
                this.ruleForm.itemList.push({
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinQualityIndexCreate : spinQualityIndexUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            checkDuplicates() {
                const namesSet = new Set();
                let hasDuplicates = false;
                this.ruleForm.itemList.forEach(item => {
                    if (namesSet.has(item.name)) {
                        hasDuplicates = true;
                    } else {
                        namesSet.add(item.name);
                    }
                });
                this.hasDuplicates = hasDuplicates;
            },
            onConfirmBtn() {
                this.checkDuplicates();
                this.$refs['ruleForm'].validate(valid => {
                    if (valid && this.hasDuplicates === false) {
                        this.createAndUpdateRequest();
                    } else {
                        if (this.hasDuplicates === true) {
                            this.$message({
                                type: 'error',
                                message: '内容有重复'
                            });
                        } else {
                            this.$tipsBar(this, 'validator');
                        }
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinQualityIndexGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
